#!/bin/sh
# $Id: cmetricd.init 6192 2007-03-09 12:53:08Z focht $
#
# chkconfig: 2345 70 40
# description: cmetricd startup script
#
### BEGIN INIT INFO
# Provides:       cmetricd
# Required-Start: $gmond
# Required-Stop:
# Default-Start:  3 5
# Default-Stop:
# Description:    Feeds Ganglia with custom cluster metrics information
### END INIT INFO

[ -f /etc/rc.d/init.d/functions ] && . /etc/rc.d/init.d/functions

FULLPATH=/usr/sbin/cmetricd
BASE=`basename $FULLPATH`
pidfile=/var/run/$BASE.pid

runpid() {
    local pid
    sleep 1
    pid=`/bin/ps -wwuroot -o pid,cmd | grep perl | grep $FULLPATH | awk '{print $1}'`
    echo $pid > $pidfile
}

running() {
    local pid running
    if [ -f $pidfile ]; then
	pid=`cat $pidfile`
	running=`ps -wwe -o cmd $pid | grep -c $FULLPATH`
	[ $running -eq 0 ] && pid=""
    else
	pid=`/bin/ps -wwuroot -o pid,cmd | grep perl | grep $FULLPATH | awk '{print $1}'`
    fi
    echo $pid
}

RETVAL=0
case "$1" in
    start)
        echo -n "Starting $BASE: "
        pid=`running`
	if [ -n "$pid" ]; then
	    echo " ... process already running on $pid"
	    exit 1
	fi
   	$FULLPATH
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && touch /var/lock/subsys/$BASE
        [ $RETVAL -eq 0 ] && runpid
        ;;
    stop)
        echo -n "Shutting down $BASE: "
	pid=`running`
	[ -n "$pid" ] && kill $pid
        RETVAL=$?
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$BASE $pidfile
	[ $RETVAL -eq 0 ] || echo " ... failed"
	echo
        ;;
    status)
	if [ -f $pidfile ]; then
	    pid=`running`
	    if [ -n "$pid" ]; then
		echo "$BASE (pid $pid) is running ..."
		exit 0
	    else
	        echo "$BASE is dead but pidfile exists"
	        exit 1
	    fi
	else
	    if [ -f /var/lock/subsys/$BASE ]; then
		echo "$BASE is dead but subsystem is locked"
		exit 2
	    fi
	fi
	echo "$BASE is stopped"
	exit 3
        ;;
    restart)
        $0 stop
        $0 start
		;;
    *)
        echo "Usage: $0 {start|stop|status}"
        exit 1
        ;;
esac

exit $RETVAL
